package com.indep2.bqrcd.web.services;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.indep2.bqrcd.web.model.InformacionCd;
import com.thoughtworks.xstream.XStream;

public class CodigoQRImpl implements CodigoQR {

	public static final int QR_HEIGTH = 128;
	public static final int QR_WIDTH = 128;

	@Override
	public BitMatrix generar(InformacionCd plantilla) {

		BitMatrix matrix = null;

		try {

			if (plantilla == null) {
				plantilla = new InformacionCd();
			}

			String xmlEntradaDatos = parseaDatos(plantilla);

			QRCodeWriter writer = new QRCodeWriter();
			matrix = writer.encode(xmlEntradaDatos, BarcodeFormat.QR_CODE,
					QR_WIDTH, QR_HEIGTH);

			// File file = new File("/home/sergio/Desktop/test.png");
			// MatrixToImageWriter.writeToFile(matrix, "PNG", file);
			// System.out.println(file.getAbsolutePath());
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return matrix;
	}

	@Override
	public String parseaDatos(InformacionCd plantilla) {

		String result = "";

		try {

			XStream parseador = new XStream();

			if (plantilla == null) {
				plantilla = new InformacionCd();
			}

			result = parseador.toXML(plantilla);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public InformacionCd recuperaDatos(String datos) {

		InformacionCd resultado = new InformacionCd();

		try {
			XStream parseador = new XStream();
			resultado = (InformacionCd) parseador.fromXML(datos);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultado;
	}

}
